/* eslint-disable @typescript-eslint/no-use-before-define */
import UploadDoc from '@/components/uploadDoc';
import UploadExcel from '@/components/uploadExcel';
import { delArticle, getArticles, getArticlesById } from '@/services/ant-design-pro/knowledge';
import { DataType } from '@/services/models/dataDoc';
import { getFileSize } from '@/utils';
import { FileAddOutlined, UploadOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { Badge, Button, Card, message, Modal, Space, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { toNumber } from 'lodash';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

const DataDoc: React.FC = () => {
  const [isOpenExcel, setIsOpenExcel] = useState<boolean>(false);
  const [isOpenDoc, setIsOpenDoc] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<DataType[]>();
  const [openDel, setOpenDel] = useState<boolean>(false);
  const [delIndex, setDelIndex] = useState<any>();
  const [openDetail, setOpenDetail] = useState<boolean>(false);
  const [detail, setDetail] = useState<string>('');
  const [totals, setTotals] = useState<number>();
  const [knowledgeId, setKnowledgeId] = useState<string>('');
  //分页默认值，
  const [pageOption, setPageOption] = useState({
    pageNo: 1, //当前页为1
    pageSize: 10, //一页8行
  });

  const deleteRow = (index: number) => {
    setOpenDel(true);
    setDelIndex(index);
  };

  const deleteRowOk = async () => {
    const { article_id } = dataSource[delIndex];
    const res = await delArticle(article_id);
    if (res.code === 0) {
      if (dataSource?.length === 1) {
        if (pageOption.pageNo > 1) {
          paginationChange(pageOption.pageNo - 1, pageOption.pageSize);
        } else {
          setDataSource([]);
        }
      } else {
        articleRes(pageOption.pageNo, pageOption.pageSize);
      }
      setOpenDel(false);
    } else {
      message.error(res.msg);
    }
  };

  const detailRow = async (index: number) => {
    setOpenDetail(true);
    const selItem = dataSource[index];
    const res = await getArticlesById(selItem.article_id);
    if (res.code === 0) {
      setDetail(res.data?.content);
    } else {
      message.error(res.msg);
    }
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      width: 80,
      // className:`${styles.f11}`,
      render: (text, record, index) =>
        `${(pageOption.pageNo - 1) * pageOption.pageSize + (index + 1)}`,
    },
    {
      title: '文档标题',
      dataIndex: 'title',
    },
    {
      title: '上传时间',
      dataIndex: 'created_at',
      sorter: (a, b) => a.created_at - b.created_at,
      render: (_, record) => `${moment(parseInt(record.created_at)).format('YYYY-MM-DD HH:mm:ss')}`,
    },
    {
      title: '文件大小',
      dataIndex: 'length',
      render: (_, record) => `${getFileSize(record.length)}`,
    },
    {
      title: '上传人',
      dataIndex: 'created_by',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, { status }) => {
        if (status === '正常') {
          return <Badge status="success" text={status} />;
        } else {
          return <Badge status="error" text={status} style={{ color: '#FC687A' }} />;
        }
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record, index) => (
        <Space>
          <a onClick={() => deleteRow(index)}>删除</a>
          <a onClick={() => detailRow(index)}>详情</a>
        </Space>
      ),
    },
  ];

  const articleRes = async (current: number, size: number) => {
    let params: any = { page: current, per_page: size };
    if (knowledgeId) {
      params.knowledge_base_id = toNumber(knowledgeId);
    }
    console.log(params);
    const res = await getArticles(params);
    if (res.code === 0) {
      const { articles, total_count } = res.data;
      setTotals(total_count);
      articles.forEach((article: any) => {
        article.key = +new Date() + Math.random();
      });
      setDataSource(articles);
    } else {
      message.error(res.msg);
    }
    return;
  };

  useEffect(() => {
    const query = history.location.search;
    if (query) {
      const kbid = query.split('?')[1].split('=')[1];
      setKnowledgeId(kbid);
    } else {
      articleRes(pageOption.pageNo, pageOption.pageSize);
    }
  }, []);

  useEffect(() => {
    if (knowledgeId) {
      articleRes(pageOption.pageNo, pageOption.pageSize);
    }
  }, [knowledgeId]);

  const updateOpenDoc = (open: boolean) => {
    setIsOpenDoc(open);
    articleRes(pageOption.pageNo, pageOption.pageSize);
  };
  const updateOpenExcel = (open: boolean) => {
    setIsOpenExcel(open);
    articleRes(pageOption.pageNo, pageOption.pageSize);
  };
  const tableSize = () => {
    return {
      width: (window.screen.availWidth * 1054) / 1440.0,
      height: (window.screen.availHeight * 500) / 810.0,
    };
  };

  //分页配置
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: () => `共${totals}条`,
    current: pageOption.pageNo,
    pageSize: pageOption.pageSize,
    total: totals,
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    onChange: (current: number, size: number) => paginationChange(current, size),
  };

  //当翻页时，改变当前为第current页，current和size这两参数是onChange API自带的，会帮你算出来你现在在第几页，这一页有多少行数据。
  const paginationChange = async (current: number, size: number) => {
    //前面用到useState
    setPageOption({
      pageNo: current, //当前所在页面
      pageSize: size, //一页有几行
    });

    articleRes(current, size);
  };

  const rowClassName = (record: any, index: any) => {
    let className = styles['light-row'];
    if (index % 2 === 1) className = styles['dark-row'];
    return className;
  };

  return (
    <div className="page-container">
      {/* <Header title={'知识库'}></Header> */}
      <div className={styles.containData}>
        <div className={styles.header} style={{ width: tableSize().width }}>
          <span style={{ fontWeight: 500 }}>数据库</span>
          <div style={{ display: 'flex', flexDirection: 'row' }}>
            <Button className={styles.upload} onClick={() => setIsOpenExcel(true)}>
              {/* <img
                src={UPLOAD_ICON}
                alt=""
                height="11px"
                width="11px"
                style={{ paddingRight: '2px' }}
              /> */}
              <UploadOutlined />
              批量上传
            </Button>
            <Button className={styles.upload} onClick={() => setIsOpenDoc(true)}>
              {/* <img
                src={UPLOAD_ICON}
                alt=""
                height="11px"
                width="11px"
                style={{ paddingRight: '2px' }}
              /> */}
              <FileAddOutlined />
              上传文档
            </Button>
          </div>
        </div>
        <Card style={{ width: tableSize().width }}>
          <Table
            columns={columns}
            className={'custom-table-style'}
            dataSource={dataSource}
            rowClassName={rowClassName}
            pagination={paginationProps}
            scroll={{ y: tableSize().height }}
            size="small"
          />
        </Card>
        {/* 删除文档弹窗 */}
        <Modal
          title={<div style={{ display: 'flex', justifyContent: 'center' }}>确定删除</div>}
          open={openDel}
          onOk={deleteRowOk}
          onCancel={() => setOpenDel(false)}
          mask={false}
          destroyOnClose
          centered
          closable
          width={300}
          footer={[
            <div key="1" style={{ display: 'flex', justifyContent: 'center', gap: '34px' }}>
              <Button onClick={() => setOpenDel(false)} style={{ width: '88px', height: '32px' }}>
                取消
              </Button>
              <Button
                type="primary"
                danger
                onClick={deleteRowOk}
                style={{ width: '88px', height: '32px' }}
              >
                确认
              </Button>
            </div>,
          ]}
        >
          <div
            style={{
              display: 'flex',
              fontSize: '14px',
              justifyContent: 'center',
              margin: '18px 0 26px',
            }}
          >
            确认删除该文档吗?
          </div>
        </Modal>
        <Modal
          title={null}
          open={openDetail}
          onCancel={() => setOpenDetail(false)}
          destroyOnClose
          closable={false}
          mask={false}
          width={415}
          footer={null}
        >
          <div className={styles.detailCon}>{detail}</div>
        </Modal>
        {isOpenDoc && (
          <UploadDoc
            knowledgeId={knowledgeId}
            updateOpenDoc={updateOpenDoc}
            open={isOpenDoc}
          ></UploadDoc>
        )}
        {isOpenExcel && (
          <UploadExcel
            knowledgeId={knowledgeId}
            updateOpenExcel={updateOpenExcel}
            open={isOpenExcel}
          ></UploadExcel>
        )}
      </div>
    </div>
  );
};

export default DataDoc;
